package com.ssyc.common.quanzi;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ssyc.common.R;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.OnloadingMoreListener;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.manager.StateBarManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.KeyBoardUtils;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.dialog.CustomDialogManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 我的圈子
 * Created by Administrator on 2018/6/25 0025.
 */
public class MyQuanziActivity extends BaseActivity implements View.OnClickListener, View.OnLayoutChangeListener, SrfManager.OnPullRefreshListener, TextWatcher, OnloadingMoreListener {

    //加载框布局
    private RelativeLayout rlLoadingView;

    //内容布局
    private RelativeLayout rlContent;

    //返回
    private RelativeLayout rlBack;

    //编辑
    private RelativeLayout rlEdit;

    //列表控件
    private RecyclerView rv;

    //下拉刷新控件
    private SmartRefreshLayout srl;

    private LinearLayout llContent;

    private EditText etInput;

    private Button btSend;

    //Activity最外层的Layout视图
    private View activityRootView;

    //屏幕高度
    private int screenHeight = 0;

    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    //适配器
    private QuanZiRvAdapter adapter;

    //数据集合
    private List<QuanZiInfo.CirclelistBean> oldDatas;

    //头布局
    private View headView;
    private ImageView lvTop, lvHead;
    private TextView tvName;

    //空视图
    private View emptyView;

    //获取评论的当前条目的位置
    private int commentPos;

    //分页
    private int page = 0;

    //时间
    private String time = "0";

    //好友关系
    private String friendlist = "";

    //界面刷新的标识
    public static final int UPDATE = 0x440;

    //区别是否是评论或者回复的标识
    private int type = 1;

    private String rowid;
    private String c2;
    private String role2;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return "";
    }

    @Override
    protected int getContentLayout() {
        return R.layout.base_activity_myquanzi;
    }

    @Override
    protected void init() {

        showContent();

        //配置状态栏颜色
        initStateColor();

        //初始化视图
        initView();

        //初始化下拉刷新
        initSrf();

        //设置列表
        initRv();

        //请求数据
        http(BqaManager.NORML);
    }


    /**
     * 配置状态栏颜色的方法
     */
    private void initStateColor() {
        //设置6.0以后沉浸状体栏的问题
        StateBarManager.setBarWithUltimateBar(this, getResources().getColor(com.ssyc.common.R.color.titlebg),
                getResources().getColor(com.ssyc.common.R.color.nav_color));
    }

    /**
     * 初始化视图
     */
    private void initView() {
        rlLoadingView = findView(R.id.rl_loading);
        rlLoadingView.setVisibility(View.VISIBLE);
        rlContent = findViewById(R.id.rl_content);
        rlContent.setVisibility(View.GONE);
        rv = findViewById(R.id.rv);
        srl = findViewById(R.id.srl);
        etInput = findViewById(R.id.et_input);
        etInput.addTextChangedListener(this);
        btSend = findViewById(R.id.bt_send);
        btSend.setOnClickListener(this);
        llContent = findViewById(R.id.ll_content);
        llContent.setOnClickListener(this);
        activityRootView = findViewById(R.id.rl_main);
        headView = View.inflate(this, R.layout.base_rv_head_myquanzi, null);
        lvTop = headView.findViewById(R.id.lv_top);
        lvHead = headView.findViewById(R.id.ivhead);

        lvHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //头像点击事件跳转到个人详情资料界面
                SPUtil.put(MyQuanziActivity.this, SpKeys.CIRCLETYPE, 1);
                Intent intent = new Intent(MyQuanziActivity.this,
                        PersonInfoActivity.class);
//                intent.putExtra("acc2", AccountUtils.getAccount(MyQuanziActivity.this));
//                intent.putExtra("role2", AccountUtils.getRole(MyQuanziActivity.this));
                startActivity(intent);
            }
        });
        tvName = headView.findViewById(R.id.tv_name);
        rlBack = findViewById(R.id.rl_back);
        rlBack.setOnClickListener(this);
        rlEdit = findViewById(R.id.rl_edit);
        rlEdit.setOnClickListener(this);

        //设置自己姓名
        tvName.setText(AccountUtils.getName(this));

        //设置自己头像
        ImageUtil.displayImage(MyQuanziActivity.this, lvHead,
                AccountUtils.getIcon(MyQuanziActivity.this),
                R.drawable.base_default_head);
    }


    /**
     * 初始化下拉刷新控件
     */
    private void initSrf() {
        //配置下拉刷新控件
        SrfManager.setSmartByPullListener(srl, this);

        //添加输入框的监听事件
        etInput.addTextChangedListener(this);

        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();

        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;
    }

    /**
     * 初始化列表控件
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        adapter = new QuanZiRvAdapter(rv, this, this,
                R.layout.base_item_rv_myquanzi, oldDatas);
        adapter.addHeaderView(headView);
    }

    /**
     * 请求服务器数据
     *
     * @param method
     */
    private void http(final int method) {

        if (method == BqaManager.NORML || method == BqaManager.PULLREFRESH) {
            page = 0;
        } else {
            page++;
        }
        Map<String, String> map = new HashMap<>();
        map.put("type", "10");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("acc2", AccountUtils.getAccount(this));
        map.put("role2", AccountUtils.getRole(this));
        if (method == BqaManager.NORML || method == BqaManager.PULLREFRESH) {
            //第一次请求时,传入时间为0
            map.put("update_time", "0");
        } else {
            //加载更多时传入当前数据源的最后一个数据的update_time
            map.put("update_time", oldDatas.get(oldDatas.size() - 1).getUpdate_time());
        }
        map.put("page", page + "");
        map.put("friendlist", friendlist);
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.QUANZI, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoadingView, srl, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoadingView != null && rlLoadingView.getVisibility() == View.VISIBLE) {
                    rlLoadingView.setVisibility(View.GONE);
                }

                if (rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {
                    QuanZiInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, QuanZiInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }


                    if (null != info) {
                        if ("200".equals(info.getState()) || "101106".equals(info.getState())) {
                            //返回成功
                            List<QuanZiInfo.CirclelistBean> newDatas;
                            newDatas = info.getCirclelist();

                            if (newDatas != null) {
                                if (method == BqaManager.NORML) {
                                    oldDatas.clear();
                                    oldDatas.addAll(newDatas);
                                    BqaManager.setRv(null, MyQuanziActivity.this,
                                            adapter, rv, MyQuanziActivity.this);

                                    //设置背景图
                                    ImageUtil.displayImage(MyQuanziActivity.this, lvTop,
                                            info.getCircle_bgimg(), R.drawable.base_common_timg);

                                } else {

                                    //更新数据
                                    BqaManager.updateRvBySmf(method, srl, rv, oldDatas, newDatas, adapter);
                                }
                            } else {
                                if ("101106".equals(info.getState())) {
                                    if (method == BqaManager.LOADINDGMORE) {

                                        //更新数据
                                        BqaManager.updateRvBySmf(method, srl, rv, oldDatas, newDatas, adapter);
                                    } else if (method == BqaManager.NORML) {

                                        newDatas = new ArrayList<QuanZiInfo.CirclelistBean>();
                                        oldDatas.clear();
                                        oldDatas.addAll(newDatas);
                                        BqaManager.setRv(null, MyQuanziActivity.this,
                                                adapter, rv, MyQuanziActivity.this);


                                    } else if (method == BqaManager.PULLREFRESH) {
                                        //更新数据
                                        BqaManager.updateRvBySmf(method, srl, rv, oldDatas,
                                                new ArrayList<QuanZiInfo.CirclelistBean>(), adapter);
                                    }
                                }
                            }
                        } else {
                            UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }


    /**
     * 下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        http(BqaManager.PULLREFRESH);
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        http(BqaManager.LOADINDGMORE);
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.rl_back) {
            //返回
            finish();
        } else if (id == R.id.rl_edit) {
            //发布圈子
            UiUtils.startActivity(this, SendCircleActivity.class);
        } else if (id == R.id.bt_send) {
            //发送评论的按钮
            sendCommentAction();
        }
    }

    /**
     * 发送评论内容的方法
     */
    private void sendCommentAction() {
        //获取输入内容
        String inputText = etInput.getText().toString().trim();
        KeyBoardUtils.closeKeyboard(etInput);
        etInput.setText("");

        //隐藏评论布局
        llContent.setVisibility(View.GONE);

        if (TextUtils.isEmpty(inputText)) {
            UiUtils.Toast("未输入评论内容", false);
            return;
        } else {

            //第三步:更新当前界面
            KeyBoardUtils.closeKeyboard(etInput);
            etInput.setText("");

            //隐藏评论布局
            llContent.setVisibility(View.GONE);

            if (type == 1) {
                //评论

                CustomDialogManager.show(this, "发布中...");
                Map<String, String> map = new HashMap<>();
                map.put("type", "6");
                map.put("acc", AccountUtils.getAccount(this));
                map.put("role", AccountUtils.getRole(this));
                map.put("circlerowid", rowid);
                map.put("platform", "8");
                map.put("content", inputText);
                HttpUtils.post(HttpAdress.COMMENT, map, this, new HttpUtils.CallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomDialogManager.dissmiss();
                        UiUtils.Toast(BaseApplication.ERROR + ",发布失败", false);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("test", response + "---评论的返回值");
                        CustomDialogManager.dissmiss();
                        if (!TextUtils.isEmpty(response)) {
                            CommentInfo info = null;
                            try {
                                info = GsonUtil.jsonToBean(response, CommentInfo.class);
                            } catch (Exception e) {
                                Log.i("test", Constants.PARSEDATAERROR);
                            }
                            if (null != info) {
                                if ("200".equals(info.getState())) {
                                    //返回成功
                                    UiUtils.Toast("发布成功", false);
                                    //通知朋友圈界面进行刷新操作
                                    BusInfo busInfo = new BusInfo();
                                    busInfo.setType(MyQuanziActivity.UPDATE);
                                    EventBus.getDefault().post(busInfo);

                                } else {
                                    UiUtils.Toast("发布失败" + Constants.ERRORSTATE + info.getState(), false);
                                    Log.i("test", Constants.ERRORSTATE + info.getState());
                                }

                            } else {
                                Log.i("test", Constants.EMPTY);
                            }

                        } else {
                            Log.i("test", Constants.EMPTY);
                        }
                    }
                });

            } else if (type == 2) {
                //回复评论

                CustomDialogManager.show(this, "发布中...");
                Map<String, String> map = new HashMap<>();
                map.put("type", "7");
                map.put("acc", AccountUtils.getAccount(this));
                map.put("role", AccountUtils.getRole(this));
                map.put("acc2", c2);
                map.put("role2", role2);
                map.put("circlerowid", rowid);
                map.put("platform", "8");
                map.put("content", inputText);
                HttpUtils.post(HttpAdress.COMMENT, map, this, new HttpUtils.CallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomDialogManager.dissmiss();
                        UiUtils.Toast(BaseApplication.ERROR + ",发布失败", false);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("test", response + "---评论的返回值");
                        CustomDialogManager.dissmiss();
                        if (!TextUtils.isEmpty(response)) {
                            CommentInfo info = null;
                            try {
                                info = GsonUtil.jsonToBean(response, CommentInfo.class);
                            } catch (Exception e) {
                                Log.i("test", Constants.PARSEDATAERROR);
                            }
                            if (null != info) {
                                if ("200".equals(info.getState())) {
                                    //返回成功
                                    UiUtils.Toast("发布成功", false);
                                    //第一步:通知朋友圈界面进行刷新操作
                                    BusInfo busInfo = new BusInfo();
                                    busInfo.setType(MyQuanziActivity.UPDATE);
                                    EventBus.getDefault().post(busInfo);

                                } else {
                                    UiUtils.Toast("发布失败" + Constants.ERRORSTATE + info.getState(), false);
                                    Log.i("test", Constants.ERRORSTATE + info.getState());
                                }

                            } else {
                                Log.i("test", Constants.EMPTY);
                            }

                        } else {
                            Log.i("test", Constants.EMPTY);
                        }
                    }
                });


            }
        }
    }


    /**
     * 加入对根据局的管理监听,主要是解决软键盘弹出和关闭的监听状态
     */
    @Override
    protected void onResume() {
        super.onResume();

        //添加layout大小发生改变监听器
        activityRootView.addOnLayoutChangeListener(this);
    }

    /**
     * 事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        if (null != busInfo && "showcontent".equals(busInfo.msg)) {
            //收到显示底部评论布局的事件和弹出软键盘的消息了
            llContent.setVisibility(View.VISIBLE);
            etInput.requestFocus();
            commentPos = busInfo.pos;
            rowid = busInfo.answerFlag;
            etInput.setHint("");
            rv.smoothScrollToPosition(busInfo.pos + 1);
            KeyBoardUtils.openKeybord(etInput);
            type = 1;
        }

        if (null != busInfo && "huifucomment".equals(busInfo.msg)) {
            //收到显示底部评论布局的事件和弹出软键盘的消息了
            llContent.setVisibility(View.VISIBLE);
            etInput.requestFocus();
            commentPos = busInfo.pos;
            String item = busInfo.answerFlag;
            List<QuanZiInfo.CirclelistBean.CommentlistBean> comments =
                    GsonUtil.jsonToBean(item, QuanZiInfo.CirclelistBean.class).getCommentlist();

            rowid = comments.get(commentPos).getCirle_row_id() + "";
            c2 = comments.get(commentPos).getUser_id();
            role2 = comments.get(commentPos).getRole() + "";

            etInput.setHint("回复" + comments.get(commentPos).getUser_name());
            KeyBoardUtils.openKeybord(etInput);
            type = 2;
        }
        //更新界面的消息
        if (null != busInfo && busInfo.getType() == UPDATE) {
            http(BqaManager.PULLREFRESH);
        }
    }

    /**
     * 监听软键盘
     */
    @Override
    public void onLayoutChange(View v, int left, int top, int right,
                               int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            if (llContent != null && llContent.getVisibility() == View.GONE) {
                llContent.setVisibility(View.VISIBLE);
            }

        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
            if (llContent != null && llContent.getVisibility() == View.VISIBLE) {
                llContent.setVisibility(View.GONE);
            }
        }
    }


    /**
     * 输入评论内容的EditText的内容改变监听
     *
     * @param charSequence
     * @param i
     * @param i1
     * @param i2
     */
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        //获取输入内容
        String inputText = etInput.getText().toString().trim();
        if (TextUtils.isEmpty(inputText)) {
            btSend.setBackgroundResource(R.drawable.quanzi_bt_no_send);
            btSend.setTextColor(getResources().getColor(R.color.unsend));
            btSend.setEnabled(false);
        } else {
            btSend.setBackgroundResource(R.drawable.quanzi_bt_send);
            btSend.setTextColor(getResources().getColor(R.color.white));
            btSend.setEnabled(true);
        }
    }
}
